package com.wusuowei.springboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wusuowei.springboot.mapper.CommentMapper;
import com.wusuowei.springboot.model.po.Comment;
import com.wusuowei.springboot.service.CommentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author LGY
 */
@Slf4j
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {


    @Resource
    private CommentMapper commentMapper;

    @Override
    public List<Comment> findCommentDetail(Integer articleId) {

        return commentMapper.findCommentDetail(articleId);
    }
    @Override
    public List<Comment> getTree(Integer id) {

        List<Comment> comments = commentMapper.selectList(new LambdaQueryWrapper<Comment>().eq(Comment::getArticleId, id));

        List<Comment> list = comments.stream().filter(item -> item.getPid().equals(0))
                .map(comment -> {
                    comment.setChildren(getChildren(comment,comments));
                    return comment;
                }).collect(Collectors.toList());
        return list;

    }

    private List<Comment> getChildren(Comment comment, List<Comment> list) {
        List<Comment> childrens = list.stream().filter(item -> {
            return item.getPid().equals(comment.getId());
        }).map(item -> {
            item.setChildren(getChildren(item, list));
            return item;
        }).collect(Collectors.toList());
        return childrens;
    }


}
